import { SyncStatus } from './domain/old_ldc/server/modules/services/sync-status';
import { TokenManager, ServiceConfig, Logger } from './common';
import { DataContextFactory } from './domain/fbsDataContext';
import { Server } from './server';
let webconfig = require("../webconfig").webconfig;
import { config } from "./domain/old_ldc/server/modules/config";
import { DataSyncWatcher } from "./common/dataSync/dataSyncWatcher"
import { CleanManager, ICleanService } from './common/dataClean/cleanManager';

//动态加载controller
for (let item of webconfig.router) {
    require("./" + item.src + ".js");
}

//测试代码，正式删除
if (process.env.NODE_ENV == "development") {
    config.fbs = "on";
}

//当前服务是CDC 或者LDC模式下面 开启FBS 则开启服务器监听
if ((config.fbs && config.fbs == "on") || webconfig.svrType === "CDC") {
    let app = new Server();
    app.listen();

    //重新加载Token列表
    TokenManager.Current.LoadFromDB();
    TokenManager.Current.LoadFromConfig();
}

CleanManager.Current.RegistCleanService(ServiceConfig.Current.GetService<ICleanService>("orderService"));
CleanManager.Current.RegistCleanService(ServiceConfig.Current.GetService<ICleanService>("tableService"));
CleanManager.Current.RegistCleanService(ServiceConfig.Current.GetService<ICleanService>("kitchenOrderService"));
CleanManager.Current.RegistCleanService(ServiceConfig.Current.GetService<ICleanService>("expeditionOrderService"));
CleanManager.Current.RegistCleanService(ServiceConfig.Current.GetService<ICleanService>("frontStoreStockService"));
CleanManager.Current.RegistCleanService(new Logger());

CleanManager.Current.CleanData();

SyncStatus.Current.setPending();
let dataSyncWatcher = DataSyncWatcher.Current;

// 自动关闭 nodejs 服务，闭关后会被 POS 自动重启
// 重启时自动收缩 nedb 文件，避免 nedb 文件过大
let startedAt: number = new Date().getTime();
// 1 分钟运行一次
setInterval(async function () {
    console.log('正在检查是否符合关闭条件');
    // 根据业务日判断重启时间
    let ctx = DataContextFactory.GetDataContext();
    let store = await ctx.Store.First();
    if (store) {
        let shutDownHour: number = store.setting.businessDuration;
        let currentTime: number = new Date().getTime();
        let currentHour: number = new Date().getHours();
        if ((currentTime - startedAt) > 1 * 3600 * 1000 && currentHour === shutDownHour) {
            console.log('符合关闭条件，服务即将关闭...')
            process.exit();
        } else {
            console.log(`不符合关闭条件，服务将在 ${shutDownHour} 点关闭...`)
        }
    } else {
        console.log(`店铺信息不存在，无法判断服务重启时间...`)
    }
}, 1 * 60 * 1000);
console.log('自动关闭服务启动完毕');

process.on('uncaughtException', (err) => {
    console.error('Unexpected Exception：', err);
    console.error(err.stack);
    new Logger().getLogger("error").info("server start at %d  pid - %d", process.env.port, process.pid);
});
